package com.lihepeng.leecode.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *  A 打印 5次 B 打印10次 C 打印15次
 */
class PrintSource1{
    private int number =1;
    private Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();
    // 判断
    public   void print5() {
        lock.lock();
        try {
            while (number!=1) {
                condition1.await();
            }
            // 干活
            for (int i=0;i<5;i++) {
                System.out.println(Thread.currentThread().getName()+"打印"+i);
            }
            // 通知
            number =2;
            condition2.signalAll();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
    public void print10() {
        lock.lock();
        try {
            while (number!=2) {
                condition2.await();
            }
            // 干活
            for (int i=0;i<10;i++) {
                System.out.println(Thread.currentThread().getName()+"打印"+i);
            }
            // 通知
            number =3;
            condition3.signalAll();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
    public void print15() {
        lock.lock();
        try {
            while (number!=3) {
                condition3.await();
            }
            // 干活
            for (int i=0;i<15;i++) {
                System.out.println(Thread.currentThread().getName()+"打印"+i);
            }
            // 通知
            number =1;
            condition3.signalAll();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

    // 干活
    // 通知
}
public class PrintDemo {
    public static void main(String[] args) {
        PrintSource1 printSource1 = new PrintSource1();
        new Thread(()->{
            for (int i=0;i<3;i++) {

                printSource1.print5();
            }
        },"t1").start();
        new Thread(()->{
            for (int i=0;i<3;i++) {
                printSource1.print10();
            }
        },"t2").start();
        new Thread(()->{
            for (int i=0;i<3;i++) {
                printSource1.print15();
            }
        },"t3").start();
    }
}
